package com.uziot.net.usoup.template;

import com.alibaba.fastjson.JSON;
import com.uziot.net.usoup.annotation.Attribute;
import com.uziot.net.usoup.annotation.Text;
import com.uziot.net.usoup.annotation.URL;
import com.uziot.net.usoup.services.ParsePageService;
import org.jsoup.nodes.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className ElementParser
 * @date 2021-06-04 14:47:53
 * @description
 */

@Service
public class ElementParser {

    @Autowired
    private ParsePageService parsePageService;

    public <T> T parse(Class<T> clazz) throws Exception {
        boolean isTableAnnotationExist = clazz.isAnnotationPresent(URL.class);
        if (!isTableAnnotationExist) {
            return null;
        }
        HashMap<String, List<String>> source = new HashMap<>(8);

        // 获取到attributeAnnotation的注解
        URL urlAnnotation = clazz.getAnnotation(URL.class);
        String urlValue = urlAnnotation.value();
        int timeout = urlAnnotation.timeout();
        HashMap<String, String> map = new HashMap<>(1);
        map.put("timeout", String.valueOf(timeout));
        Document document = (Document) parsePageService.parsePage(urlValue, map);

        // 获取到所有的字段
        Field[] arrayFields = clazz.getDeclaredFields();
        for (Field field : arrayFields) {
            // 获取到attributeAnnotation的注解
            boolean attributeExist = field.isAnnotationPresent(Attribute.class);
            if (attributeExist) {
                Attribute attributeAnnotation = field.getAnnotation(Attribute.class);
                String value = attributeAnnotation.value();
                String type = attributeAnnotation.type();
                String fieldName = field.getName();
                List<String> attribute = parsePageService.parseElements(document, value, type);
                source.put(fieldName, attribute);
            }
            // 获取到textAnnotation的注解
            boolean textExist = field.isAnnotationPresent(Text.class);
            if (textExist) {
                Text textAnnotation = field.getAnnotation(Text.class);
                String element = textAnnotation.element();
                String type = textAnnotation.type();
                String fieldName = field.getName();
                List<String> texts = parsePageService.parseElements(document, element, type);
                source.put(fieldName, texts);
            }
        }
        String json = JSON.toJSONString(source);
        T t = JSON.parseObject(json, clazz);
        return t;
    }

    public ParsePageService getParsePageService() {
        return parsePageService;
    }

    public void setParsePageService(ParsePageService parsePageService) {
        this.parsePageService = parsePageService;
    }
}
